package rmhc.api.vk
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.Security;
	import flash.utils.Dictionary;
	import rmhc.gui.customTrace;
	import rmhc.gui.SupplyFunctions;
	
	import rmhc.api.dataflow.UserInfo;
	import rmhc.api.tasks.IGetFriends;
	
	public class GetFriends extends VkApiTask implements IGetFriends
	{
		protected static const THUMB_FIELD:String = "photo_medium_rec";
		
		protected var friends:Vector.<UserInfo>;
		
		protected var loaders:Dictionary;
		protected var friendsCount:int , loadedCount:int;
		//protected var pre:Dictionary;
		
		
		public function GetFriends(wrapper:VkApi)
		{
			//customTrace("GetFriends.GetFriends");
			var fields:String = THUMB_FIELD + ",sex";
			super(wrapper, "friends.get" , { "fields" : fields } );
		}
		
		override public function parseData(result:Object):void
		{
			//customTrace("GetFriends.parseData result" + SupplyFunctions.objectToString(result));
			friendsCount = result.length;
			loadedCount = 0;
			loaders = new Dictionary();
			friends = new Vector.<UserInfo>();
			var u:UserInfo;
			for (var i:int = 0; i < result.length; i++) 
			{
				u = parseUserInfo( result[i] );
				u.thumbSrc = result[i][THUMB_FIELD];
				if ( u.thumbSrc.match( "deactivated" ) )
				{
					u.thumbSrc = null;
				}
				friends.push( u );
				//loaders[preloadOne( result[i] )] = u;
			}
			onComplete();
		}
		
		/*protected function preloadOne( friendData:Object ):Loader
		{
			////customTrace("GetFriends.preloadOne ");
			////customTrace("GetFriends:preloadOne: friendData = " +SupplyFunctions.objectToString(friendData));
			var req:URLRequest = new URLRequest( friendData[PHOTO_FIELD] );
			var lod:Loader = new Loader();
			Security.loadPolicyFile(SupplyFunctions.getServerURL(friendData[PHOTO_FIELD])+'crossdomain.xml')
			lod.contentLoaderInfo.addEventListener(Event.COMPLETE , onLoadOne );
			lod.load( req );
			return lod;
		}
		protected function onLoadOne( e:Event ):void
		{
			var li:LoaderInfo = e.target as LoaderInfo;
			var lod:Loader = li.loader;
			var u:UserInfo = loaders[lod];
			u.thumb = ( lod.content as Bitmap ).bitmapData;
			if ( ++loadedCount >= friendsCount )
			{
				//customTrace("GetFriends.onLoadOne onComplete();");
				onComplete();
			}
		}*/
		
		public function getFriends():Vector.<UserInfo>
		{
			return friends;
		}
	}
}